package com.uziot.bucket.advice.response;

import com.alibaba.fastjson.JSON;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.AbstractGenericHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 功能描述: <br>CommonJsonWrapper
 * 统一返回格式
 * 自定义HttpMessageConverter可能会导致返回不是期望的结果
 *
 * @author shidt
 * @date 2020-03-09 0:44
 */
@ControllerAdvice
@SuppressWarnings("ALL")
public class CommonJsonWrapper implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {

        //获取当前处理请求的controller的方法
        String methodName = returnType.getMethod().getName();
        boolean annotationPresent = returnType.getMethod().isAnnotationPresent(NativeResponse.class);
        if (annotationPresent) {
            return false;
        }

        return !DefaultResponse.class.isAssignableFrom(returnType.getParameterType()) ||
                !ResponseEntity.class.isAssignableFrom(returnType.getParameterType());
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (AbstractGenericHttpMessageConverter.class.isAssignableFrom(selectedConverterType)) {
            return DefaultResponse.builder().data(body).build();
        } else {
            return JSON.toJSONString(DefaultResponse.builder().data(body).build());
        }

    }
}
